package com.lidong.zc.databasemodel.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 实现 ApplicationContextAware 接口 setApplicationContext方法中赋值
 *
 * @author LiDong
 */
@Component
public class LowcodeDbSpringContextUtils implements ApplicationContextAware {

    private static final Logger logger = LoggerFactory.getLogger(LowcodeDbSpringContextUtils.class);

    /**
     * 上下文对象实例
     */
    private static ApplicationContext applicationContext;

    private LowcodeDbSpringContextUtils() {
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (Objects.isNull(LowcodeDbSpringContextUtils.applicationContext)) {
            logger.debug("SpringContextUtils init...");
            LowcodeDbSpringContextUtils.applicationContext = applicationContext;
        }
        logger.debug("SpringContextUtils init success...");
    }

    /**
     * 获得当前的ApplicationContext
     *
     * @return ApplicationContext
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 根据名称拿到 Bean
     *
     * @param name Bean 的名称
     * @return Object
     */
    @SuppressWarnings("all")
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    /**
     * 从ApplicationContext中获得Bean并且转型
     *
     * @param tClass 类
     * @param <T>    T
     * @return T
     */
    public static <T> T getBean(Class<T> tClass) {
        return applicationContext.getBean(tClass);
    }

    /**
     * 获取 bean
     *
     * @param beanName bean 名称
     * @param clazz    类
     * @param <T>      T
     * @return T
     */
    public static <T> T getBean(String beanName, Class<T> clazz) {
        return applicationContext.getBean(beanName, clazz);
    }
}

